package com.xc.file.web.rest.open;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.api.basic.BasicApi;
import com.xc.config.aspect.AspectConstants;
import com.xc.core.bean.OpenFileBean;
import com.xc.core.dto.FileDto;
import com.xc.core.dto.SignDto;
import com.xc.core.enums.EffectStatus;
import com.xc.file.config.Constants;
import com.xc.file.entity.FileEntity;
import com.xc.file.entity.FolderEntity;
import com.xc.file.enums.FailCode;
import com.xc.file.service.FileService;
import com.xc.file.service.FolderService;
import com.xc.tool.utils.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>开放接口，文件管理</p>
 *
 * @author xc
 * @version v1.0.0
 */
@Api(tags = "开放接口，文件管理")
@RestController
public class OpenFileRest {
    @Autowired
    private FileService fileService;
    @Autowired
    private BasicApi basicApi;
    @Autowired
    private AspectConstants aspectConstants;
    @Autowired
    private Constants constants;
    @Autowired
    private FolderService folderService;

    @ApiOperation(value = "删除文件", notes = "开放接口")
    @DeleteMapping(value = "/open/file")
    public void deleteOpenFile(@ModelAttribute OpenFileBean openFileBean) {
        // 验证权限
        openFileBean.setAuthorityCode("deleteOpenFile");
        openFileBean.setMyAppId(aspectConstants.getAppId());
        SignDto signDto = basicApi.verifySign(openFileBean);
        List<FileEntity> entities = verifyFileParam(openFileBean, signDto.getUserId());
        for (FileEntity fileEntity : entities) {
            if (!fileService.removeById(fileEntity.getId())) {
                throw FailCode.DELETE_FILE_FAIL.getOperateException();
            }
        }
    }

    @ApiOperation(value = "获取文件", notes = "开放接口")
    @GetMapping(value = "/open/file")
    public List<FileDto> getOpenFile(@ModelAttribute OpenFileBean openFileBean) {
        openFileBean.setAuthorityCode("getOpenFile");
        openFileBean.setMyAppId(aspectConstants.getAppId());
        SignDto signDto = basicApi.verifySign(openFileBean);
        List<FileEntity> entities = verifyFileParam(openFileBean, signDto.getUserId());
        return ObjectUtils.convertList(entities, FileDto.class);
    }

    @ApiOperation(value = "修改文件状态为有效", notes = "开放接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件状态", name = "status", paramType = "path", required = true),
    })
    @PutMapping("/open/file_status/{status}")
    public List<FileDto> updateOpenFileStatus(@ModelAttribute OpenFileBean openFileBean, @PathVariable String status) {
        openFileBean.setAuthorityCode("updateOpenFileStatus");
        openFileBean.setMyAppId(aspectConstants.getAppId());
        SignDto signDto = basicApi.verifySign(openFileBean);
        List<FileEntity> entities = verifyFileParam(openFileBean, signDto.getUserId());
        for (FileEntity fileEntity : entities) {
            if ("valid".equals(status)) {
                fileEntity.setStatus(EffectStatus.VALID.getStatus());
            }
            if ("invalid".equals(status)) {
                fileEntity.setStatus(EffectStatus.INVALID.getStatus());
            }
            if (!fileService.updateById(fileEntity)) {
                throw FailCode.UPDATE_FILE_FAIL.getOperateException();
            }
        }
        return ObjectUtils.convertList(entities, FileDto.class);
    }

    /**
     * 验证文件参数
     *
     * @param openFileBean 参数
     * @return 文件信息
     */
    private List<FileEntity> verifyFileParam(OpenFileBean openFileBean, String userId) {
        // 获取文件信息
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        boolean bool = true;
        for (String path : openFileBean.getPaths()) {
            if (path != null && !"".equals(path) && userId != null && !"".equals(userId)) {
                bool = false;
                addPath(queryWrapper, path, userId);
            }
        }
        for (String url : openFileBean.getUrls()) {
            if (url != null && !"".equals(url) && userId != null && !"".equals(userId) && url.contains("http")) {
                try {
                    String urlPath = new URL(url).getPath();
                    String path = constants.getOpenDownloadUrl() + userId;
                    if (urlPath.contains(path)) {
                        bool = false;
                        String filePath = urlPath.substring(path.length());
                        addPath(queryWrapper, filePath, userId);
                    }
                } catch (Exception e) {
                    throw FailCode.URL_ANALYSIS_ERROR.getOperateException();
                }
            }
        }
        if (!bool) {
            return fileService.list(queryWrapper);
        }
        return new ArrayList<>();
    }

    /**
     * 添加path
     *
     * @param queryWrapper 查询条件
     * @param path         path路径
     * @param userId       用户id
     */
    private void addPath(QueryWrapper<FileEntity> queryWrapper, String path, String userId) {
        String folderPath = "";
        String fileName = path;
        if (path.contains("/")) {
            folderPath = path.substring(0, path.lastIndexOf("/"));
            fileName = path.substring(path.lastIndexOf("/") + 1);
        }
        FolderEntity folderEntity = folderService.getFolderByPath(userId, folderPath);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("folder_id", folderEntity.getId());
        queryWrapper.eq("name", fileName);
        queryWrapper.or();
    }
}
